<?php
/**
 * Created by PhpStorm.
 * User: kxy
 * Date: 2019/2/21
 * Time: 上午9:26
 */

namespace App\Ant;

use App\Models\GenerateUrl;
use App\Models\PushUrl;
use Illuminate\Support\Collection;
use Iterator;

class UrlIterator implements Iterator
{

    protected $urls;

    protected $status;

    public function __construct(array $urls, $status = 0)
    {
        $this->urls = $urls;
        $this->status = $status;
    }

    /**
     * Return the current element
     * @link http://php.net/manual/en/iterator.current.php
     * @return mixed Can return any type.
     * @since 5.0.0
     */
    public function current()
    {
        $current = current($this->urls);
        $ke = explode('.', $this->key());
        $path = 'public/push';
        $name = $path . '/' . $ke[0] . '.txt';
        if (!\Storage::exists($path)) {
            \Storage::makeDirectory($path);
        }
        $arr = '';
        $ids = [];
        foreach ($current as $value) {
            $arr .= $value['url'] . "\n";
            $ids[] = $value['id'];
        }
        file_put_contents(\Storage::path($name), $arr, $this->status);
        unset($arr);
        $url = 'http://' . $this->key() . \Storage::url($name);
        if (GenerateUrl::where('url', $url)->first() == null) {
            $gem = new GenerateUrl(['url' => $url]);
            $gem->save();
        }
        if ($ids) {
            PushUrl::whereIn('id', $ids)->update(['generate_status' => true]);
        }
        return;
    }

    /**
     * Move forward to next element
     * @link http://php.net/manual/en/iterator.next.php
     * @return void Any returned value is ignored.
     * @since 5.0.0
     */
    public function next()
    {
        return next($this->urls);
    }

    /**
     * Return the key of the current element
     * @link http://php.net/manual/en/iterator.key.php
     * @return mixed scalar on success, or null on failure.
     * @since 5.0.0
     */
    public function key()
    {
        return key($this->urls);
    }

    /**
     * Checks if current position is valid
     * @link http://php.net/manual/en/iterator.valid.php
     * @return boolean The return value will be casted to boolean and then evaluated.
     * Returns true on success or false on failure.
     * @since 5.0.0
     */
    public function valid()
    {
        return key($this->urls) !== null;
    }

    /**
     * Rewind the Iterator to the first element
     * @link http://php.net/manual/en/iterator.rewind.php
     * @return void Any returned value is ignored.
     * @since 5.0.0
     */
    public function rewind()
    {
        return reset($this->urls);
    }
}